package xuegao.study.mall.order.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import xuegao.study.mall.repo.dao.oms.OmsCarItemDao;
import xuegao.study.mall.common.model.oms.OmsCartItem;
import xuegao.study.mall.order.service.OmsCarItemService;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OmsCarItemServiceImpl implements OmsCarItemService {

    @Autowired
    private OmsCarItemDao omsCarItemDao;

    @Override
    public Boolean add(OmsCartItem cartItem) {
        OmsCartItem existsOmsCarItem = getCarItem(cartItem);
        int count;
        if (existsOmsCarItem == null) {
            cartItem.setCreateDate(new Date());
            count = omsCarItemDao.insert(cartItem);
        } else {
            existsOmsCarItem.setModifyDate(new Date());
            existsOmsCarItem.setQuantity(existsOmsCarItem.getQuantity() + cartItem.getQuantity());
            count = omsCarItemDao.updateByPrimaryKey(existsOmsCarItem);
        }
        return count > 0;
    }

    @Override
    public List<OmsCartItem> list(Long memberId) {
        Map<String, Object> params = new HashMap<>();
        params.put("memberId", memberId);
        params.put("deleteStatus", 0);
        return omsCarItemDao.selectByParams(params);
    }

    private OmsCartItem getCarItem(OmsCartItem cartItem) {
        Long memberId = cartItem.getMemberId();
        Long productId = cartItem.getProductId();
        Map<String, Object> params = new HashMap<>();
        params.put("memberId", memberId);
        params.put("productId", productId);
        params.put("deleteStatus", 0);
        if (cartItem.getProductSkuId() != null) {
            params.put("productSkuId", cartItem.getProductSkuId());
        }
        List<OmsCartItem> cartItemList = omsCarItemDao.selectByParams(params);
        if (!CollectionUtils.isEmpty(cartItemList)) {
            return cartItemList.get(0);
        }
        return null;
    }
}
